<template>
  
  <ContentWrap>

  <el-row >

    <el-col :span="14" style="padding: 5px">

        <el-card shadow="never">

          <el-date-picker
            
            v-model="queryParams.date"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="选择日期查看可挂号医师"
            class="!w-240px"
            @change="handleDateChange"
          />
          
          <el-table 
            :data="viewDoctorList" 
            v-loading="loading"
            style=" max-height: 500px; margin-top: 16px; overflow-y: auto"
            v-if="queryParams.date"
          >
            <el-table-column prop="nickname" label="医师姓名" />
            <el-table-column prop="deptName" label="所属科室" />
            <el-table-column label="时段">
              <template #default="scope">
                {{ getIntDictOptions(DICT_TYPE.MEDICAL_REGISTER_PERIOD).find(dict => dict.value === scope.row.period)?.label }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button size="small" @click="selectDoctor(scope.row)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

    <el-col :span="10" style="padding: 5px;">
      <el-card
        shadow="never"
        
        class="box-card"
        style="width: 100%"
      >
      <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
      
    >
    <el-row>
      <el-form-item label="科类" prop="deptId">
        <el-tree-select
              v-model="queryParams.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择挂号科室"
              class="!w-240px"

        />
        <el-button 
          type="primary" 
          link
          style="margin-left: 10px"
          :disabled="!queryParams.deptId"
           @click="openForm()"
        >
          查看部门医师
        </el-button>
      </el-form-item>
    </el-row>

    <el-row>
      <el-form-item label="挂号日期" prop="date">
        <el-date-picker
          v-model="queryParams.date"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="日期"
          class="!w-120px"
          
        />
      </el-form-item>
    </el-row>

    <el-row>
      <el-form-item label="时段" prop="period">
             <el-select
              v-model="queryParams.period"
              placeholder="选择时段"
              clearable
              class="!w-100px"
              @change="handlePeriodChange"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.MEDICAL_REGISTER_PERIOD)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
      </el-form-item>
      
      <el-form-item label="问诊时间" prop="consultingTime">
        <el-time-select
          v-model="queryParams.consultingTime"
          placeholder="问诊时间"
          class="!w-120px"
          :start="getTimeRange().start"
          :end="getTimeRange().end"
          :step="'00:30'"
          :disabled="!queryParams.period"
        />
      </el-form-item>
    </el-row>
    <el-row>
      <el-form-item label="医师" prop="doctorId">
            <el-select 
              v-model="queryParams.doctorId" 
              placeholder="请选择排班医师"
              clearable
              style="width: 150px"
              :disabled="showTable"
             >
              <el-option
                v-for="doctor in doctorList"
                :key="doctor.id"
                :label="doctor.nickname"
                :value="doctor.id"
              />
            </el-select>
      </el-form-item>
    </el-row>

    <el-row justify="center">
      <el-form-item >
        <el-button
            link
            type="primary"
            @click="openDoctorTable(queryParams.doctorId)"
            :disabled="globalStatus === 'disbabled'"
          >
            确认
        </el-button>
      </el-form-item>
      <el-form-item>
          <el-button
            link
            type="danger"
            @click="handleCancle()"
          >
            重置
          </el-button>
      </el-form-item>
    </el-row>
    </el-form>
      </el-card>
    </el-col>
    </el-row>

  </ContentWrap>

  

  <div style="margin-top: 20px" v-if="showTable">
  <ContentWrap>
    <el-descriptions  
      title="医师信息"
      :column="1"
      border
      label-align="right"
      :label-width="68">
      <el-descriptions-item label="姓名">{{ formData.nickname }}</el-descriptions-item>
      <el-descriptions-item label="性别">{{ getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX).find(item => item.value === formData.sex)?.label }}</el-descriptions-item>
      <el-descriptions-item label="肖像">
        <el-image
          :src="formData.avatar"
          :preview-src-list="[formData.avatar]"
          :preview-teleported="true"
          :preview-close-on-click-modal="false"
          :preview-close-on-press-escape="false"
          :fit="formData.avatar ? 'contain' : 'cover'"
          :preview="formData.avatar ? true : false"
          style="width: 100px; height: 100px"
        />
      </el-descriptions-item>
      <el-descriptions-item label="医师类别">{{ formData.typeName }}</el-descriptions-item>
      <el-descriptions-item label="挂号费">{{ formData.cost }}</el-descriptions-item>

      <el-descriptions-item label="医师描述">{{ formData.remark }}</el-descriptions-item>
    </el-descriptions>

    <div style="margin-top: 20px; text-align: center; ">
      <el-button 
      type="primary" 
      @click="handleConfirmDoctor(formData.id)"
      :disabled="globalStatus === 'disbabled'"
      >确认并挂号</el-button>
    </div>
  </ContentWrap>
  </div>

  <!-- 二维码支付弹窗 -->
  <el-dialog
  v-model="qrCodeVisible"
  :title="qrCodeTitle"
  width="30%"
  center
>
  <div style="text-align: center">
    <img :src="qrCodeUrl" style="width: 200px; height: 200px" />
    <p style="margin-top: 20px">请使用手机扫描二维码完成支付</p>
  </div>
</el-dialog>

<DeptDoctorForm ref="formRef" @success="openForm"/>

</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { generateQRCode } from '@/utils/qrcode' // 添加二维码生成工具
import * as DeptApi from '@/api/system/dept'
import * as DoctorApi from '@/api/medical/doctor'
import * as RegisterApi from '@/api/medical/register'
import * as CostApi from '@/api/medical/cost'
import { defaultProps, handleTree } from '@/utils/tree'
import { ref, reactive, onMounted } from 'vue'
import { useI18n } from 'vue-i18n' // 请替换为实际的国际化插件导入
import { getUserProfile } from '@/api/system/user/profile'
import DeptDoctorForm from './DeptDoctorForm.vue' // 导入组件

defineOptions({ name: 'MedicalUserRegister' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const globalStatus = ref() // 全局状态
const deptList = ref<any[]>([]) // 添加部门列表ref
const doctorList = ref([])// 用户列表
const viewDoctorList = ref([]) // 查看医生列表
const getDeptId = ref() // 科室id
const getPeriod = ref() // 时段
const getDate = ref() // 日期 
const showTable = ref(false) // 新增：控制表格显示状态
const loading = ref(false) // 表格加载状态
const costNumber = ref() // 费用
const qrCodeVisible = ref(false) // 控制二维码弹窗显示
const qrCodeUrl = ref('') // 存储二维码图片URL
const qrCodeTitle = ref('') // 弹窗标题

const timer = ref<NodeJS.Timeout>() // 轮询定时器
/** 获取登录用户信息 */
const userId = ref()
const allDeptId = 115 // 所有科室id
const registerStatus = ref() // 挂号状态

const queryParams = reactive({
  deptId: undefined,
  doctorId: undefined,
  consultingTime: '',
  date: '',
  name: undefined,
  period: undefined,
  status: undefined
})

const formData = ref({
  id: undefined,
  nickname: '',
  sex: undefined,
  doctorType: undefined,
  typeName: '',
  cost: undefined,
  avatar: '',
  remark: '',
})

const registerForm = ref({
  id:'',
  doctorId: '',
  patientsId: '',
  deptId: '',
  date: '' as string | Date, // 明确类型
  consultingTime: '',
  period: undefined,
  cost: undefined,
  registerStatus: undefined,
  description: '',
  createTime: ''
})

const queryFormRef = ref() // 搜索的表单
const refreshTable = ref(true) // 重新渲染表格状态


/** 添加/修改操作 */
const formRef = ref()
const openForm = () => {
  if (queryParams.deptId === undefined) {
  message.error('请先选择挂号科室')
  return
  }
  console.log('传递的科室ID:', queryParams.deptId); // 添加调试日志
  formRef.value.open(queryParams.deptId)
}


const getUserInfo = async () => {
  const users = await getUserProfile()
  console.log('用户信息:', users)
  if (users.identify === '' || users.mobile === '') {
    message.error('请先完善个人信息, 再进行挂号操作，包含手机号与身份证号')
    globalStatus.value = 'disbabled'
  }
  userId.value = users.id
  console.log('用户id:', userId.value)
}

const getCostInfo = async (doctorId) => {
  if (!doctorId) {
    message.error('请选择医师')
    return
  }
  const cost = await CostApi.getCostByDoctor(doctorId)
  costNumber.value = cost.cost
  formData.value.typeName = cost.typeName
  console.log('获取的费用信息：', costNumber.value)
  formData.value.cost = costNumber.value
}


/** 禁用今天之前的日期 */
const disabledDate = (time: Date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return time.getTime() < today.getTime()
}

const handleDateChange = async (date) => {
  if (date) {
    await getViewDoctorList()
  }
}



const selectDoctor = (doctor) => {
  queryParams.doctorId = doctor.id
  queryParams.period = doctor.period
  queryParams.deptId = doctor.deptId
  getPeriod.value = doctor.period
  openDoctorTable(doctor.id)
}

/** 获取时间范围 */
const getTimeRange = () => {
  if (queryParams.period === 1) { // 上午时段
    return { start: '09:00', end: '11:30' }
  } else if (queryParams.period === 2) { // 下午时段
    return { start: '14:00', end: '17:30' }
  }
  return { start: '09:00', end: '17:30'} // 默认全时段
}


/** 打开医生表格 */
const openDoctorTable = async (doctorId) => {
  if (!doctorId) {
    message.error('请选择医师')
    return
  }
  showTable.value = true // 显示表格
  formData.value = await DoctorApi.getDoctor(doctorId)
  getCostInfo(doctorId) // 获取费用信息
}

/** 取消操作 */
const handleCancle = () => {
  queryParams.deptId = undefined
  queryParams.doctorId = undefined
  queryParams.consultingTime = ''
  queryParams.date = ''
  queryParams.period = undefined
  showTable.value = false
}

/**获取医师列表 */
const getDoctorList = async () => {
  try {
    getDeptId.value = queryParams.deptId
    getPeriod.value = queryParams.period
    getDate.value = queryParams.date
    if (!getDeptId.value) {
      message.error('请选择科室')
      return
    }
    console.log('getDeptId:', getDeptId.value)
    console.log('period:', getPeriod.value)
    const response = await DoctorApi.getDeptDoctorList(getDeptId.value, getPeriod.value, getDate.value)
    console.log('response:', response)
    doctorList.value = response
    console.log('获取的父用户列表：', doctorList.value)
  } catch (error) {
    console.error('获取父用户列表失败:', error)
    message.error('获取父用户列表失败')
  }
}

const getViewDoctorList = async () => {
  try {
    getPeriod.value = queryParams.period
    getDate.value = queryParams.date
    
    console.log('period:', getPeriod.value)
    const response = await DoctorApi.getDoctorSchedule(getDate.value)
    console.log('response:', response)
    viewDoctorList.value = response
  } catch (error) {
    message.error('获取失败')
  }
}

/** 生成支付二维码 */
const generatePaymentQRCode = async (costNumber) => {
  qrCodeTitle.value = `需要缴费 ${costNumber} 元`
  // 生成一个模拟支付链接，实际项目中替换为真实支付接口
  const paymentUrl = `https://payment.example.com/pay?amount=${costNumber}&timestamp=${Date.now()}`
  qrCodeUrl.value = await generateQRCode(paymentUrl)
  qrCodeVisible.value = true
  return new Promise((resolve) => {
    // 模拟扫码支付成功，3秒后自动返回true
    setTimeout(() => {
      qrCodeVisible.value = false
      resolve(true)
    }, 5000)
  })
}

/** 确认选择医师 */
const handleConfirmDoctor = async (doctorId) => {
  if(queryParams.consultingTime === '') {
    message.error('请选择问诊时间')
    return
  }
  registerStatus.value = 0
  // 这里可以添加业务逻辑，如提交选择、关闭弹窗等
  registerForm.value.doctorId = doctorId
  registerForm.value.patientsId = userId.value
  registerForm.value.date = getDate.value
  registerForm.value.consultingTime = queryParams.consultingTime
  registerForm.value.period = getPeriod.value
  registerForm.value.cost = costNumber.value
  registerForm.value.registerStatus = registerStatus.value
  const data = registerForm.value as unknown as RegisterApi.MRegisterVO

  loading.value = true
  const getThis = ref()
  try {
    getThis.value = await RegisterApi.createRegister(data)
    if (getThis.value === 404404404) {
      message.error('相同时段已经挂号')
      loading.value = false
      showTable.value = false // 隐藏医师信息展示
      return
    }
    
  } catch (error) {
    message.error('挂号失败')
    loading.value = false
    return
  }
  

  // 生成支付二维码(使用真实的订单ID和金额)
  qrCodeVisible.value = true
  // 生成并显示支付二维码
  const paymentSuccess = await generatePaymentQRCode(costNumber.value)
  if (paymentSuccess) {
    registerStatus.value = 1
    registerForm.value.registerStatus = registerStatus.value
    registerForm.value.id = getThis.value.id
    const changeStatus = 2
    await RegisterApi.updateRegisterStatus(getThis.value, changeStatus)
    message.success('挂号成功')
  }

  resetForm()
  doctorList.value = [] // 重置医师选择栏的数据
 
  loading.value = false
  showTable.value = false // 隐藏医师信息展示
  
}



const handlePeriodChange = (newValue) => {
  if (newValue === null || newValue === undefined) {
    // 当 period 取消选值时，重置医师选择栏的数据
    queryParams.doctorId = undefined
    doctorList.value = []
  } else {
    // 这里调用你原本的 onPeriodChange 方法
    onPeriodChange(newValue);
  }
};

/** 时段选择改变时触发 */
const onPeriodChange = async (value) => {
  if (!queryParams.date) {
    message.info('选择日期后获取当日挂号医师')
    return
  }
  await getDoctorList()
  console.log('时段值变化为:', value);
}

/** 重置表单 */
const resetForm = () => {
  Object.assign(queryParams, {
    deptId: undefined,
    doctorId: undefined,
    consultingTime: '',
    date: '',
    name: undefined,
    period: undefined,
    status: undefined
  })
}

/** 初始化 **/
onMounted(async () => {
   // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptDoctorList())
  getUserInfo()
  // 组件卸载时清理定时器
  return () => {
    if (timer.value) clearInterval(timer.value)
  }
})
</script>
<style scoped>
.centered-container {
  text-align: center;
}

.centered-container > * {
  display: inline-block;
}

</style> 